import 'package:flutter/material.dart';
import 'package:ninetyfour/manger/user_manger.dart'; 
import '../homeView/sdetail_top_view.dart'; 
import '../../manger/network_utils.dart'; 
import '../../models/serach_info_model.dart'; 
import '../homeView/search_none_view.dart'; 
import '../../components/loading_widget.dart'; 
import 'package:ninetyfour/l10n/app_localizations.dart'; 
import '../../services/home_info_manager.dart'; 
import '../../models/home_init_model.dart'; 
import '../../components/currency_select_widget.dart'; 
import '../../class/controller/product_detail.dart';
import '../../manger/umevent_utils.dart';
import '../../manger/qysdk_manger.dart';
import '../../manger/uniqueIdentifier_manager.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../homeView/search_item_view.dart';

class SearchDetailPage extends StatefulWidget {
  final String serachKey;
  const SearchDetailPage({super.key,  required this.serachKey}); 
 
  @override 
  _SearchDetailPageState createState() => _SearchDetailPageState();
}
 
class _SearchDetailPageState extends State<SearchDetailPage> {
  List<PageDataListModel> pageDataListModel = [];
  List<TypeListModel> typeListModel = [];
  List<CurrencyListModel> currencyList = [];
  List<PageDataListNoModel> noDataList = [];
  bool _showCurrencySelect = false;
  var selectPath = 0;
  var searchKey = "";
  final ValueNotifier<bool> loadingNotifier = ValueNotifier(false);
  bool isDataLoaded = false; // 用于控制是否加载过数据
  RefreshController refreshController = RefreshController(initialRefresh: false);

  int _emptyDataCount = 0;         // 统计次数
  DateTime? _firstEmptyDataTime;   // 记录第一次空数据的时间
  int pageNum = 1; // 页眉
  @override
  void initState() {
    super.initState();
    final homeManager = HomeInfoManager();
    currencyList = homeManager.homeInitModel?.currencyList ?? [];
    searchKey = widget.serachKey;
    WidgetsBinding.instance.addPostFrameCallback((_) => loadData());
    loadSearchNoData();
  }

  Future<void> loadData({bool isRefresh = false}) async {
    UmengEvent.trackEvent("home_search_click","搜索按钮点击",widget.serachKey);
    if (loadingNotifier.value) return; // 如果正在加载，则不重复加载
    
    loadingNotifier.value = true;
    if (isRefresh) {
      pageNum ++ ;
    } else {
      pageNum = 1; // 刷新时重置页码
    }

    try {
      final response = await NetworkUtils.post(
        isSimplifiedChinese() ? RequestCmd.pageList : RequestCmd.pageListen,
        body: {"name": searchKey, "pageNum": pageNum, "pageSize": 12},
        loadingNotifier: loadingNotifier,
      );
      final model = PageListModel.fromJson(response);
      if (isRefresh) {
        refreshController.refreshCompleted();
      }
      if (model.code == 200) {
        final newData = model.data?.list ?? [];
        if (newData.isNotEmpty) {
          if (isRefresh) {
            isDataLoaded = true; // 刷新时标记为已加载
            pageDataListModel.addAll(newData);
            setState(() {});
            refreshController.loadComplete();
          } else {
            pageDataListModel = newData;
            await loadData2();
          }
        } else {
          setState(() {
            // pageDataListModel.clear();
            isDataLoaded = true; // 没有数据时也标记为加载完成
          });
          if (isRefresh) {
            refreshController.loadComplete();
          } else {
            pageDataListModel = [];
          }
          handleNoDataTrigger();
        }
      } else {
        handleNoDataTrigger();
        setState(() {
          pageDataListModel.clear();
          isDataLoaded = true; // 如果请求失败，标记加载完成
        });
        if (isRefresh) {
          refreshController.loadComplete();
        } else {
          pageDataListModel = [];
        }
      }
    } catch (e) {
      setState(() {
        pageDataListModel.clear();
        isDataLoaded = true; // 捕获异常后，标记为加载完成
      });
      if (isRefresh) {
        refreshController.loadComplete();
      }
    } finally {
      loadingNotifier.value = false;
    }
  }

  handleNoDataTrigger() {
    // 空数据计数逻辑
    final now = DateTime.now();
    if (_firstEmptyDataTime == null ||
        now.difference(_firstEmptyDataTime!).inSeconds > 60) {
      // 超过一分钟，重置计数
      _firstEmptyDataTime = now;
      _emptyDataCount = 1;
    } else {
      _emptyDataCount++;
      if (_emptyDataCount >= 3) {
        // 一分钟内累计三次
        QYSDK.showQYSession();
        // 清空计数
        _emptyDataCount = 0;
        _firstEmptyDataTime = null;
      }
    }
  }

  Future<void> loadData2() async {
    try {
      final response = await NetworkUtils.post(
        isSimplifiedChinese() ? RequestCmd.searchDetail : RequestCmd.searchListen,
        body: {"spuId": pageDataListModel[selectPath].spuId},
      );
      final model = SearchDetailModel.fromJson(response);

      if (model.code == 200) {
        setState(() {
          typeListModel = model.data?.rechargeTypeList ?? [];
          isDataLoaded = true; // 数据加载完成
        });
      }
    } catch (e) {
      setState(() {
        isDataLoaded = true; // 捕获异常后，标记为加载完成
      });
    } finally {
      loadingNotifier.value = false;
    }
  }

  Future<void> loadSearchNoData() async {
   try {
      final response = await NetworkUtils.get(
        RequestCmd.action,
        params: {"uid": await UniqueIdentifierManager().getUniqueIdentifier()},
      );

      final model = PageSerachNoModel.fromJson(response);
      
      if (model.code == 200) {
        if (model.data?.h5.isNotEmpty ?? false) {
          setState(() {
            noDataList = model.data?.h5 ?? [];
          });
        }
        
      } 
    } catch (e) {
      print('Error loading search no data: $e');
    }
  }

  @override
  void dispose() {
    loadingNotifier.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F6F7),
      body: Stack(
        children: [
          // 主页面内容
          ValueListenableBuilder<bool>(
            valueListenable: loadingNotifier,
            builder: (context, isLoading, _) {
              return _buildContent();
            },
          ),
          LoadingWidget(isLoading: loadingNotifier),
          if (_showCurrencySelect)
            CurrencySelectWidget(
              currencyList: currencyList,
              top: 100,
              onSelect: (selectedCurrency) {
                setState(() {    
                  _showCurrencySelect = false;
                  UserInfos.shared.currencyListModel = selectedCurrency;
                  loadData();
                });
              },
            ),
        ],
      ),
    );
  }

Widget _buildContent() {
  return SmartRefresher(
    controller: refreshController,
    enablePullUp: true,
    enablePullDown: false,
    onLoading: () {
      loadData(isRefresh: true);
    },
    primary: false,
    footer: ClassicFooter(
      loadingText: AppLocalizations.of(context)!.loading,
      idleText: AppLocalizations.of(context)!.releaseToLoad,
      canLoadingText: AppLocalizations.of(context)!.releaseToLoad,
    ),
    child: !isDataLoaded
        ? CustomScrollView(
            slivers: [
              SliverToBoxAdapter(
                child: SDetailTopView(
                  searchKey: searchKey,
                  typeListModel: typeListModel,
                  onSearch: (searchText) {
                    setState(() {
                      searchKey = searchText;
                      loadData();
                    });
                  },
                  onBack: () => Navigator.pop(context),
                  onUnfold: (isUnfold) =>
                      setState(() => _showCurrencySelect = isUnfold),
                  isUnfold: _showCurrencySelect,
                  isDataLoaded: isDataLoaded,
                ),
              ),
            ],
          )
        : pageDataListModel.isEmpty
            ? CustomScrollView(
                slivers: [
                  SliverFillRemaining(
                    hasScrollBody: false,
                    child: Center(
                      child: SearchNoneView(
                        searchKey: searchKey,
                        pushDetail: (spuId) {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) =>
                                  ProductDetailPage(spuId: spuId),
                            ),
                          );
                        },
                        noDataList: noDataList,
                        clickCustom: () {
                          QYSDK.showQYSession();
                        },
                        onSearch: (searchText) {
                          setState(() {
                            searchKey = searchText;
                            loadData();
                          });
                        },
                        searchController:
                            TextEditingController(text: searchKey),
                        onBack: () => Navigator.pop(context),
                        onUnfold: (isUnfold) =>
                            setState(() => _showCurrencySelect = isUnfold),
                        isUnfold: _showCurrencySelect,
                      ),
                    ),
                  ),
                ],
              )
            : CustomScrollView(
                slivers: [
                  /// 顶部搜索栏
                  SliverToBoxAdapter(
                    child: SDetailTopView(
                      searchKey: searchKey,
                      typeListModel: typeListModel,
                      onSearch: (searchText) {
                        setState(() {
                          searchKey = searchText;
                          loadData();
                        });
                      },
                      onBack: () => Navigator.pop(context),
                      onUnfold: (isUnfold) =>
                          setState(() => _showCurrencySelect = isUnfold),
                      isUnfold: _showCurrencySelect,
                      isDataLoaded: isDataLoaded,
                    ),
                  ),

                  /// 相关商品标题
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 10),
                      child: Text(
                        "  " + AppLocalizations.of(context)!.relatedGoods,
                        style: const TextStyle(
                          fontSize: 16,
                          color: Color(0xFF000000),
                        ),
                      ),
                    ),
                  ),

                  /// 商品网格
                  SliverPadding(
                    padding: const EdgeInsets.symmetric(horizontal: 10),
                    sliver: SliverGrid(
                      delegate: SliverChildBuilderDelegate(
                        (context, index) {
                          final model = pageDataListModel[index];
                          return ProductGridItem(
                            spuId: model.spuId,
                            name: model.name,
                            pic: model.pic,
                          );
                        },
                        childCount: pageDataListModel.length,
                      ),
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: 10,
                        mainAxisSpacing: 10,
                        childAspectRatio: 1 / (1 + 30 / 100),
                      ),
                    ),
                  ),
                ],
              ),
  );
}

}
